package com.jair.crawler.opm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;

public class TableParser {
	public HtmlTable findTabel(HtmlPage page2) throws IOException{
		HtmlInput dba = page2.getElementByName("SqlQuery[schema]");
        dba.setValueAttribute("10.136.4.47:3334|bpm");
        HtmlTextArea sql = page2.getElementByName("SqlQuery[sql]");
        sql.setText("select * from `tb_asset_apply_record`");
        HtmlElement Querybtn = (HtmlElement) page2.getElementById("processbutton");
        HtmlPage ret = Querybtn.click();
        DomNode node = ret.querySelector(".sql-result");
        HtmlTable table =  (HtmlTable) node.getByXPath("//table").get(0);
        return table;
	}
	public List<Map<String,String>> getTableList(HtmlTable table){
		  List<HtmlTableRow> rows = table.getBodies().get(0).getRows();
   	   List<HtmlTableCell> cellList = table.getHeader().getRows().get(0).getCells();
   	   List<String> headerList = new ArrayList<String>();
   	   List<Map<String,String>> resultMap =  new ArrayList<Map<String,String>>();
   	    for(HtmlTableCell cell : cellList) {
   	    	 String columnName = cell.getTextContent();
   	    	 columnName = StringUtils.lowerCase(columnName);
   	    	 columnName = StringUtils.replace(columnName, " ", "_");
   	    	 headerList.add(columnName);
   	     }
	     	for (HtmlTableRow row : rows) {
	     		List<HtmlTableCell> cells = row.getCells();
	     		Map<String,String> map = new HashMap<String,String>();
	     		for (int i=0 ; i< cells.size() ;i++){
	     			map.put(headerList.get(i), cells.get(i).getTextContent());
	     			//file.write(' '+cell.getTextContent());
	     		}
	     		resultMap.add(map);
	     		//file.write('\n');
	     	}
	     	return resultMap;
	}
}
